package example.controller;

import example.utils.DistributedLockHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redis")
public class RedisLockController_For_Util {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DistributedLockHandler distributedLockHandler;

    /**
     * redis.opsForValue() 实现
     *
     * @return
     */
    @RequestMapping("/practice")
    public String practice() {
        String uuid = UUID.randomUUID().toString();
        String lockKey = "lockKey";
        String store = "qing";
        try {
            boolean lock = distributedLockHandler.lock(lockKey, uuid, 6000, TimeUnit.MILLISECONDS, 3000);
            if (!lock) {
                return "服务器繁忙，请稍后重试。。。";
            }
            int qing = Integer.parseInt(redisTemplate.opsForValue().get(store));
            if (qing > 0) {
                int realQing = qing - 1;
                redisTemplate.opsForValue().set(store, realQing + "");
                System.out.println("扣减成功，库存剩余：" + redisTemplate.opsForValue().get(store));
            } else {
                System.out.println("Error, 库存不足");
            }
        } finally {
            distributedLockHandler.releaseLock(lockKey, uuid);
        }
        return "Success";
    }
}
